package com.kevin.es.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

/**
 * @author kevin
 * 条件查询
 */
public class EStest_Doc_Query_By {

    public static void main(String[] args) throws Exception {

        // 创建es客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        // 查询数据
        SearchRequest request = new SearchRequest();
        request.indices("user");

        // 构建查询条件（全部查询）
        SearchSourceBuilder source = new SearchSourceBuilder()
                .query(QueryBuilders.termQuery("age", 30));

        // 添加查询资源
        request.source(source);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());

        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        // 关闭es客户端
        client.close();
    }
}
